package com.sophie.chapter3;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;

import java.time.Duration;
import java.util.Arrays;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 指定位移消费
 */
public class SeekToEnd extends ConsumerClientConfig {

    public static final String topic = "heima";

    public static void main(String[] args) {
        Properties properties = initConfig();
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);
        consumer.subscribe(Arrays.asList(topic));
        // timeout参数设置多少合适？太短会使分区分配失败，太长又有可能造成一些不必要的等待
        consumer.poll(Duration.ofMillis(2000));
        // 获取消费者所有分配到的分区
        Set<TopicPartition> assignment = consumer.assignment();
        // 判断是否分配到了分区
        while (assignment.size() == 0) {
            consumer.poll(Duration.ofMillis(100));
            assignment = consumer.assignment();
        }
        // 指定从分区末尾开始消粉
        Map<TopicPartition, Long> offsets = consumer.endOffsets(assignment);
        for (TopicPartition tp : assignment) { // consumer.seek(tpf offsets.get(tp));
            // consumer.seek (tp, offsets.get(tp);
            consumer.seek(tp, offsets.get(tp) + 1);
            System.out.println(assignment);
            System.out.println(offsets);
            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
                    // consume the record.
                    for (ConsumerRecord<String, String> record : records) {
                        System.out.println(record.offset() + ":" + record.value());
                    }
            }
        }
    }
}